package leetcode1_50;

/**
 * @Author: Zhihj
 * @Date: 2024-01-15 22:53:16
 */

/**
 * 题目链接
 * https://leetcode.wang/leetCode-2-Add-Two-Numbers.html
 */
public class Add_Two_Numbers {

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1;
        ListNode q = l2;
        ListNode curr = dummyHead;
        //进位
        int carry = 0;
        //代表两个数相加后的结果
        int sum = 0;
        while (p != null || q != null){
            int x = (p != null)?p.val:0;
            int y = (q != null)?q.val:0;
            sum = x + y + carry;
            carry = sum / 10;
            //将相加后的数存放到一个ListNode中
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            //将指针指向下一个操作数
            if(p != null){
                p = p.next;
            }
            if(q!=null){
                q= q.next;
            }
        }
        if (carry > 0){
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

    public static void main(String[] args) {
        ListNode list1 = new ListNode(2);
        list1.next = new ListNode(4);
        list1.next.next = new ListNode(3);

        ListNode list2 = new ListNode(5);
        list2.next = new ListNode(6);
        list2.next.next = new ListNode(4);
        ListNode listNode = addTwoNumbers(list1, list2);
        while (listNode != null){
            System.out.print(listNode.val);
            listNode = listNode.next;
        }
    }

}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x){
        val = x;
    }
}
